<?php
/**
 * 座位表页面
 * 相对路径: usr/biao.php
 * 作者: 15058593138@qq.com
 */

$room = isset($_GET['room']) ? safeStr($_GET['room']) : '';
if (empty($room)) {
    echo '<script>alert("教室参数错误");history.back();</script>';
    exit;
}

// 获取座位信息
$rooms = readJson('./inc/weici.json.php');
$roomInfo = null;
foreach ($rooms as $r) {
    if ($r['room'] === $room) {
        $roomInfo = $r;
        break;
    }
}

if (!$roomInfo) {
    echo '<script>alert("教室不存在");history.back();</script>';
    exit;
}

// 获取节次信息
$jiecis = readJson('./inc/jieci.json.php');

// 处理Ajax请求 - 获取座位状态
if (isset($_GET['act']) && $_GET['act'] === 'getstatus') {
    $date = isset($_POST['date']) ? safeStr($_POST['date']) : '';
    $jieci = isset($_POST['jieci']) ? safeStr($_POST['jieci']) : '';
    
    if (empty($date) || empty($jieci)) {
        jsonMsg(0, '参数错误');
    }
    
    $db = new DB();
    $db->autoCreateDateTable($date);
    $recTable = TB_PREFIX . 'recs_' . $date;
    
    $userId = $_SESSION['user_phone'];
    
    // 获取已预定座位
    $sql = "SELECT `iwei`, `usid` FROM `{$recTable}` WHERE `room` = '{$room}' AND `days` = '{$jieci}' AND `stats` = 1";
    $booked = $db->getAll($sql);
    
    $bookedSeats = [];
    foreach ($booked as $b) {
        $bookedSeats[$b['iwei']] = [
            'mine' => ($b['usid'] === $userId),
            'usid' => $b['usid']
        ];
    }
    
    $db->close();
    jsonMsg(1, '获取成功', $bookedSeats);
}

// 处理Ajax请求 - 预定座位
if (isset($_GET['act']) && $_GET['act'] === 'book') {
    $date = isset($_POST['date']) ? safeStr($_POST['date']) : '';
    $jieci = isset($_POST['jieci']) ? safeStr($_POST['jieci']) : '';
    $seat = isset($_POST['seat']) ? safeStr($_POST['seat']) : '';
    
    if (empty($date) || empty($jieci) || empty($seat)) {
        jsonMsg(0, '参数错误');
    }
    
    $db = new DB();
    $db->autoCreateDateTable($date);
    $recTable = TB_PREFIX . 'recs_' . $date;
    
    $userId = $_SESSION['user_phone'];
    
    // 检查该座位是否已被预定
    $sql = "SELECT * FROM `{$recTable}` WHERE `room` = '{$room}' AND `days` = '{$jieci}' AND `iwei` = '{$seat}' AND `stats` = 1";
    if ($db->getRow($sql)) {
        jsonMsg(0, '该座位已被预定');
    }
    
    // 检查用户该时间段是否已预定
    $sql = "SELECT * FROM `{$recTable}` WHERE `usid` = '{$userId}' AND `days` = '{$jieci}' AND `stats` = 1";
    if ($db->getRow($sql)) {
        jsonMsg(0, '您该时间段已有预定');
    }
    
    // 创建预定
    $unid = makeUnid();
    $hema = makeHema($date);
    
    $data = [
        'unid' => $unid,
        'usid' => $userId,
        'room' => $room,
        'ijie' => $date,
        'days' => $jieci,
        'iwei' => $seat,
        'hema' => $hema,
        'stats' => 1
    ];
    
    if ($db->insert($recTable, $data)) {
        $db->close();
        jsonMsg(1, '预定成功');
    } else {
        $db->close();
        jsonMsg(0, '预定失败');
    }
}

require_once './inc/head.php';
?>

<div class="container">
    <div style="background:#fff; padding:15px; border-radius:5px; margin-bottom:10px;">
        <h3><?php echo $roomInfo['name']; ?> (<?php echo $room; ?>)</h3>
        
        <div style="display:flex; gap:10px; margin-top:10px; flex-wrap:wrap;">
            <div class="form-group" style="flex:1; min-width:150px;">
                <label>选择日期</label>
                <input type="date" id="selectDate" class="form-control" 
                       value="<?php echo date('Y-m-d', strtotime('+1 day')); ?>"
                       min="<?php echo date('Y-m-d', strtotime('+1 day')); ?>"
                       max="<?php echo date('Y-m-d', strtotime('+' . YU_TIAN . ' days')); ?>">
            </div>
            
            <div class="form-group" style="flex:1; min-width:150px;">
                <label>选择节次</label>
                <select id="selectJieci" class="form-control">
                    <?php foreach ($jiecis as $j): ?>
                        <option value="<?php echo $j['code']; ?>">
                            <?php echo $j['name']; ?> (<?php echo $j['start']; ?>-<?php echo $j['end']; ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group" style="display:flex; align-items:flex-end;">
                <button class="btn btn-primary" onclick="refreshSeats()">刷新状态</button>
            </div>
        </div>
        
        <div style="margin-top:15px; font-size:12px;">
            <span style="margin-right:15px;">
                <span style="display:inline-block; width:20px; height:20px; background:#fff; border:2px solid #28a745; vertical-align:middle;"></span>
                可选
            </span>
            <span style="margin-right:15px;">
                <span style="display:inline-block; width:20px; height:20px; background:#ccc; vertical-align:middle;"></span>
                已约
            </span>
            <span>
                <span style="display:inline-block; width:20px; height:20px; background:#dc3545; vertical-align:middle;"></span>
                我的
            </span>
        </div>
    </div>
    
    <div style="background:#fff; padding:20px; border-radius:5px; overflow-x:auto;">
        <div style="text-align:center; margin-bottom:10px; color:#666;">
            前方 ← 讲台黑板 →
        </div>
        <div id="seatGrid" class="seat-grid">
            <!-- 座位将通过JS动态生成 -->
        </div>
        <div style="text-align:center; margin-top:10px; color:#666; font-size:12px;">
            左前方：门 | 右后方：门
        </div>
    </div>
</div>

<script>
    const room = '<?php echo $room; ?>';
    const layout = '<?php echo $roomInfo['layout']; ?>';
    let selectedSeat = null;
    let autoRefreshTimer = null;
    
    // 生成座位布局
    function generateSeats() {
        const rows = layout.split('|');
        const grid = document.getElementById('seatGrid');
        let html = '';
        let seatNum = 1;
        
        rows.forEach(rowSeats => {
            html += '<div class="seat-row">';
            for (let i = 0; i < parseInt(rowSeats); i++) {
                html += `<div class="seat available" data-seat="${seatNum}" onclick="selectSeat(${seatNum})">${seatNum}</div>`;
                seatNum++;
            }
            html += '</div>';
        });
        
        grid.innerHTML = html;
    }
    
    // 刷新座位状态
    function refreshSeats() {
        const date = document.getElementById('selectDate').value.replace(/-/g, '');
        const jieci = document.getElementById('selectJieci').value;
        
        ajax('index.php?do=biao&act=getstatus&room=<?php echo $room; ?>', { room: '<?php echo $room; ?>', date: date, jieci: jieci}, function(res) {
            if (res.code === 1) {
                updateSeatStatus(res.data);
            } else {
                toast(res.msg, 'error');
            }
        });
    }
    
    // 更新座位状态
    function updateSeatStatus(bookedSeats) {
        const seats = document.querySelectorAll('.seat');
        seats.forEach(seat => {
            const seatNum = seat.getAttribute('data-seat');
            seat.className = 'seat available';
            seat.onclick = function() { selectSeat(seatNum); };
            
            if (bookedSeats[seatNum]) {
                if (bookedSeats[seatNum].mine) {
                    seat.className = 'seat mine';
                } else {
                    seat.className = 'seat occupied';
                    seat.title = '已被 ' + bookedSeats[seatNum].usid + ' 预定';
                    seat.onclick = null;
                }
            }
        });
    }
    
    // 选择座位
    function selectSeat(seatNum) {
        selectedSeat = seatNum;
        
        const date = document.getElementById('selectDate').value;
        const jieci = document.getElementById('selectJieci').value;
        const jieciText = document.getElementById('selectJieci').selectedOptions[0].text;
        
        showModal('确认预定', 
            `<p>教室：<?php echo $roomInfo['name']; ?></p>
             <p>日期：${date}</p>
             <p>节次：${jieciText}</p>
             <p>座位：${seatNum}号</p>`,
            [
                {text: '取消', class: 'btn-secondary', onclick: 'closeModal()'},
                {text: '确认预定', class: 'btn-primary', onclick: 'confirmBook()'}
            ]
        );
    }
    
    // 确认预定
    function confirmBook() {
        const date = document.getElementById('selectDate').value.replace(/-/g, '');
        const jieci = document.getElementById('selectJieci').value;
        
        closeModal();
        showLoading();
        
        ajax('index.php?do=biao&act=book&room=<?php echo $room; ?>', {
            room: '<?php echo $room; ?>',
            date: date,
            jieci: jieci,
            seat: selectedSeat
        }, function(res) {
            hideLoading();
            if (res.code === 1) {
                toast(res.msg, 'success');
                refreshSeats();
            } else {
                toast(res.msg, 'error');
            }
        });
    }
    
    // 页面加载
    window.onload = function() {
        generateSeats();
        refreshSeats();
        
        // 自动刷新
        autoRefreshTimer = setInterval(refreshSeats, window.autoRefresh * 1000);
    };
    
    // 日期或节次改变时刷新
    document.getElementById('selectDate').onchange = refreshSeats;
    document.getElementById('selectJieci').onchange = refreshSeats;
</script>

<?php require_once './inc/foot.php'; ?>